import global from "./global"
import config from "./config"
// Learn TypeScript:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/typescript.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html


// /** 
//  * 获取玩家openid
//  *
//  * */
// export function GetOpenId(): void{
//     let GET = "https://api.weixin.qq.com/sns/jscode2session?appid=wxfa990215de592f7a&secret=dd70057f7c2fd450a2157e27c09796d3&js_code=";
//     console.log(GET)
//     wx.login(
//         {success: (res) => {
//             //console.log(res.code)
//             var code = res.code;
//             GET = GET + code + "&grant_type=authorization_code"
//             //console.log(url1)
//             //使用url来获得user open id

//             wx.request({ 
//                 url: GET, 
//                 success: (response) => {
//                     config.openId = response.data.openid;
//                     config.isopenId = true;
//                     console.log(config.openId);
//                 },
//                 fail: () => null,
//                 complete: () => null,
//                 data: null,
//                 header: {},
//                 method: null,
//                 dataType: null,
//                 responseType: null,
//                 })
//             },
//             fail: () => null,
//             complete: () => null,
//     })


//     /*
//     let code;
//     wx.login(code);
//     var GET = "https://api.weixin.qq.com/sns/jscode2session?appid=wxfa990215de592f7a&secret=dd70057f7c2fd450a2157e27c09796d3&js_code="  + code + "&grant_type=authorization_code"
//     let responsed;
//     wx.request(responsed); 
//     //console.log('openid:' + responsed.data.openid)
//     *
// }



/** 
 * 初始化云
 *
 * */
export function initCloud() {
    // console.log("初始化云！");
    wx.cloud.init({ env: wx.cloud.DYNAMIC_CURRENT_ENV });
    const db = wx.cloud.database({ env: wx.cloud.DYNAMIC_CURRENT_ENV });
    global.dataBase = db;
    getCloudBreaking((res) => {
        if (res.data.length == 0) {
            global.maxBreakingLevel = 0;
            updataCloudBreaking(0);
        }
        else {
            global.maxBreakingLevel = res.data[0].breakLevel;
        }
    })
}

export function updataCloudBreaking(breakLevel: number) {
    const gameInfoCollection = global.dataBase.collection('gameInfo');
    gameInfoCollection.where({
        _openid: '{openid}' // 填入当前用户 openid
    }).count({
        success: function (res) {
            // console.log(res.total)
            if (res.total == 1) {
                gameInfoCollection
                    .where({
                        _openid: '{openid}'
                    })
                    .update({
                        data: {
                            nickName: global.player.nickname,
                            breakLevel: breakLevel,
                            updateTime: new Date().toLocaleString(),
                        },
                    })
                // .then( res => {
                //     console.log(res);
                // })
            }
            else {
                if (res.total > 1) {
                    gameInfoCollection
                        .where({
                            _openid: '{openid}'
                        })
                        .remove()
                    // .then( res => {
                    //     console.log(res);
                    // })
                }
                gameInfoCollection.add({
                    // data 字段表示需新增的 JSON 数据
                    data: {
                        // _id: '{openid}', // 可选自定义 _id，在此处场景下用数据库自动分配的就可以了
                        // due: new Date("2018-09-01"),
                        nickName: global.player.nickname,
                        breakLevel: breakLevel,
                        updateTime: new Date().toLocaleString(),
                    },
                    // success: function(res) {
                    //     // res 是一个对象，其中有 _id 字段标记刚创建的记录的 id
                    //     console.log(res)
                    // },
                    fail: console.error,
                    complete: console.log
                })
            }
        },
        fail: console.error
    })
}

export function getCloudBreaking(callback: (res) => any) {
    const gameInfoCollection = global.dataBase.collection('gameInfo');
    gameInfoCollection.where({
        _openid: '{openid}' // 填入当前用户 openid
    }).get().then(res => {
        // console.log(res);
        !!callback && callback(res);
        // console.log(res.data)
    })
}

export function preloadAllResources() {
    // loadResourcesRemote(config.backgroundURL, '.jpg');
    // loadResourcesRemote(config.fixedStarURL, '.png');
    // loadResourcesRemote(config.undiscoveredplanetURL, '.png');
    // loadResourcesRemote(config.discoveredPlanetURL, '.png');
    // loadResourcesRemote(config.spaceShipURL, '.png');
    // loadResourcesRemote(config.spaceStationURL, '.png');
    // loadResourcesRemote(config.ins1URL, '.png');
    // loadResourcesRemote(config.ins2URL, '.png');
    // loadResourcesRemote(config.ins3URL, '.png');
    // loadResourcesRemote(config.ins4URL, '.png');
    // loadResourcesRemote(config.ins5URL, '.png');
    // loadResourcesRemote(config.ins6URL, '.png');
    loadResourcesRemote(config.HomeMusicURL, '.mp3');
    loadResourcesRemote(config.HomeTapSoundURL, '.mp3');
    loadResourcesRemote(config.GameEndSoundURL, '.mp3');
    loadResourcesRemote(config.GameGrabSoundURL, '.mp3');
    loadResourcesRemote(config.GameShootSoundURL, '.mp3');
}

export function loadResourcesRemote(url: string, type: string) {
    cc.assetManager.loadRemote(url, { ext: type }, (err, texture) => { });
}

export function loadingdefaultavatar(f: cc.SpriteFrame) {
    let url = "images/avatarMan"
    // console.log("加载默认头像中");
    cc.loader.loadRes(
        url,
        cc.SpriteFrame,
        (err, texture) => {
            if (err)
                return;
            f = texture;
        })
}

export function showpic(url: string, sprite: cc.Sprite, callback?: (err: Error) => any): void {
    cc.loader.loadRes(url, cc.SpriteFrame, (err, texture) => {
        if (err) {
            !!callback && callback(err);
            return;
        }
        sprite.spriteFrame = texture;
        !!callback && callback(err);
    })

}

/**
 * 获取随机值
 * @param Min 随机范围的最小值
 * @param Max 随机范围的最大值
 */
export function randomNum(Min, Max): number {
    var Range = Max - Min;
    var Rand = Math.random();
    var num = Min + Math.floor(Rand * Range);
    return num;
}


/**
 * 能设置随机种子的获取随机值
 */
export class Random {
    /**
     * 创建一个随机数生成器
     */
    public constructor(seed: number) {
        this.seed = seed;
        if (!this.seed && this.seed != 0) {
            this.seed = new Date().getTime();
        }
    }
    /**
     * 设置用于随机数生成器的种子，如果不设置则实际是取当前时间毫秒数
     */
    public seed: number;

    /**
     * 返回一个随机数，在0.0～1.0之间
     */
    public get value(): number {
        return this.range(0, 1);
    }
    /**
     * 返回一个在min和max之间的随机浮点数
     */
    public range(min: number, max: number): number {
        if (!this.seed && this.seed != 0) {
            this.seed = new Date().getTime();
        }
        max = max || 1;
        min = min || 0;
        this.seed = (this.seed * 9301 + 49297) % 233280;
        var rnd = this.seed / 233280.0;
        return min + rnd * (max - min);
    }
    /**
     * 设置用于随机数生成器的种子，如果不设置则实际是取当前时间毫秒数
     */
    public static seed: number;
}